import { Component, OnInit, ViewChild } from '@angular/core';
import { STComponent, STColumn } from '@delon/abc';
import { applyCC } from '@shared';
import { _HttpClient, ModalHelper, SettingsService } from '@delon/theme';
import { NzNotificationService } from 'ng-zorro-antd';
import { DataSourceEditComponent } from './edit/datasource-edit.component';

/**
 * 数据源管理
 */
@Component({
  selector: 'app-datasource-conf',
  templateUrl: './datasource.component.html',
})
export class DataSourceComponent implements OnInit {
  auth_btn_add = false;
  auth_btn_edit = false;
  auth_btn_del = false;
  url = `/cf/admin/dsconf/page`;
  params = { key: '' };

  @ViewChild('st', { static: false }) st: STComponent;
  columns: STColumn[] = applyCC([
    { title: '序号', index: 'id' },
    { title: '名称', index: 'name' },
    { title: '编码', index: 'code' },
    { title: '驱动', index: 'driver', ccChecked: false },
    { title: 'jdbcUrl', index: 'url', width: 150 },
    { title: '用户名', index: 'username' },
    { title: '密码', index: 'password' },
    { title: '创建时间', index: 'createDate', type: 'date', ccChecked: false },
    { title: '更新时间', index: 'updateDate', type: 'date', ccChecked: false },
    {
      ccDisabled: true,
      title: '操作',
      buttons: [
        {
          text: '编辑',
          type: 'static',
          modal: { component: DataSourceEditComponent, paramsName: 'record' },
          click: 'reload',
          iif: (item: STColumn) => {
            return this.auth_btn_edit;
          },
        },
        {
          text: '删除',
          type: 'del',
          pop: {
            title: '确定删除数据源？',
            okType: 'danger',
          },
          click: (record, _modal, comp) => {
            this.http.delete(`/cf/admin/dsconf/${record.id}`).subscribe(res => {
              if (res.status === 200) {
                this.notice.success('成功', `成功删除数据源`);
                comp!.load();
              }
            });
          },
          iif: (item: STColumn) => {
            return this.auth_btn_del;
          },
        },
      ],
    },
  ]);

  constructor(
    private http: _HttpClient,
    private modal: ModalHelper,
    private notice: NzNotificationService,
    private settings: SettingsService,
  ) {}

  ngOnInit() {
    this.auth_btn_add = this.settings.user.permissions.datasource_add_btn;
    this.auth_btn_edit = this.settings.user.permissions.datasource_edit_btn;
    this.auth_btn_del = this.settings.user.permissions.datasource_del_btn;
  }

  add() {
    this.modal.createStatic(DataSourceEditComponent, { i: { id: 0 } }).subscribe(() => this.st.reload());
  }
}
